import glob
import os
import random

import collate.icu

def main():
    path = os.path.dirname(__file__)
    for filename in glob.glob(os.path.join(path, "*", "*.list.txt")):
        fileobj = open(os.path.join(path, filename), "rU")
        locale = os.path.basename(os.path.dirname(filename))

        original = [line.decode("utf-8").strip()
                    for line in fileobj
                    if line.strip()]
        contents = list(original)

        collator = collate.icu.Collator(locale, "utf-8")

        ordered = sorted(contents, key=collator.sortemekey)
        if ordered != original:
            print "Failed to sort sorted", filename
            print "  " + "\n  ".join([line.encode("utf-8") for line in ordered])
            continue

        contents.reverse()
        ordered = sorted(contents, key=collator.sortemekey)
        if ordered != original:
            print "Failed to sort reversed", filename
            print "  " + "\n  ".join([line.encode("utf-8") for line in ordered])
            continue

        random.shuffle(contents)
        ordered = sorted(contents, key=collator.sortemekey)
        if ordered != original:
            print "Failed to sort shuffled", filename
            print "  " + "\n  ".join([line.encode("utf-8") for line in ordered])
            continue

        print "Sorted", filename, "successfully."
        
if __name__ == "__main__":
    main()
